<template>
   <a-modal
      :title="`角色权限分配 - ${currentRole.name || ''}`"
      :open="visible"
      :width="800"
      :confirm-loading="permissionModalLoading"
      @cancel="closePermissionModal"
      @ok="handlePermissionSave"
      okText="保存"
      cancelText="取消"
    >
      <a-row :gutter="16" style="height: 400px;">
        <!-- 权限分类 -->
        <a-col :span="6" style="height: 100%;">
          <div class="permission-categories">
            <a-list
              item-layout="horizontal"
              :data-source="permissionCategories"
              
            >
             <template #renderItem="{ item }">
                <a-list-item @click="handlePermissionCategoryClick(item)"
                 :class="{ 'active-category': activeCategory === item.key }">
                     <a-list-item-meta
                    :description="`${item.children.length}项权限`"
                  >
                  <template #title>
                         {{ item.name }}
                    </template>
                  </a-list-item-meta>
                </a-list-item>
             </template>
            </a-list>
          </div>
        </a-col>
        
        <!-- 权限列表 -->
        <a-col :span="18">
          <div class="permission-list">
            <div class="permission-actions">
              <div class="permission-category-title">{{ activeCategory }}</div>
              <div>
                <a-checkbox 
                v-model:checked="checkAllPermissions"
                @change="handleCheckAllPermissions"
              >
                全选
              </a-checkbox>
              <a-button 
                type="text" 
                @click="resetPermissionChecks"
              >
                重置
              </a-button>
              </div>
            </div>
            
            <div class="permission-list-container" v-for="item in permissionCategories" :key="item.key" v-show="activeCategory == item.key">
                <div class="permission-item" v-for="children in item.children">
                    <a-checkbox :value="children.key" :checked="checkedPermissionKeys.includes(children.key)" @change="handleCheckPermissions($event,children.key,item)">
                        <div>{{ `${children.key} - ${children.name}`  }}</div>
                    </a-checkbox>
                </div>
            </div>
          </div>
        </a-col>
      </a-row>
    </a-modal>
</template>

<script setup>
    import { ref } from 'vue'
    import { assignPermissions } from '@/api/role'
    import { message } from 'ant-design-vue'
    const props = defineProps({
      currentRole: {
        type: Object,
        default: () => ({})
      },
      permissionCategories: {
        type: Array,
        default: () => []
      },
    })
  

    const visible = ref(false)
    const activeCategory = ref('')
    const checkedPermissionKeys = ref([])
    const checkAllPermissions = ref(false)
    const handleCheckAllPermissions = (e) => {
      const checkCurrentCategory = props.permissionCategories.find(item=>item.key === activeCategory.value).children
      console.log(checkCurrentCategory)
      if(!checkCurrentCategory.length) {
        return
      }
      const checkedKeys = checkCurrentCategory.map(item=>item.key)
      if(e.target.checked){
        const newArr = checkedPermissionKeys.value.concat(checkedKeys)
        checkedPermissionKeys.value = [...new Set(newArr)]
      }else{
        checkedPermissionKeys.value = checkedPermissionKeys.value.filter(item=>!checkedKeys.includes(item))
      }
      console.log(checkedPermissionKeys.value)

    }
    const resetPermissionChecks = () => {
      checkAllPermissions.value = false
      const checkCurrentCategory = props.permissionCategories.find(item=>item.key === activeCategory.value).children
      const checkedKeys = checkCurrentCategory.map(item=>item.key)
      checkedPermissionKeys.value = checkedPermissionKeys.value.filter(item=>!checkedKeys.includes(item))
    }
    const handleCheckPermissions = (e,key,_item) => {
      const { children } = _item
       if(e.target.checked){
          checkedPermissionKeys.value.push(key)
          isCheckedAll(children)
       }else{
        checkedPermissionKeys.value = checkedPermissionKeys.value.filter(item=>item !== key)
        checkAllPermissions.value = false
       }
    }
    // 监听 checkAllPermissions
   
    const permissionModalLoading = ref(false)
    
    const handlePermissionCategoryClick = (item) => {
        activeCategory.value = item.key
        isCheckedAll(item.children)
    }

    const isCheckedAll = (children) => {
      const currentItemKeys = children.map(i=>i.key)
      const intersectionArr = checkedPermissionKeys.value.filter(item=>currentItemKeys.includes(item))
      checkAllPermissions.value = currentItemKeys.length === intersectionArr.length ? true : false
    }
    const closePermissionModal = () => {
        visible.value = false
    }

    const handlePermissionSave = async () => {
        console.log(props.currentRole)
        const {isAdmin} = props.currentRole
        if(isAdmin){
          message.error('超级管理员角色不能分配权限')
          return
        }

        permissionModalLoading.value = true
        try {
            await assignPermissions(props.currentRole.id, checkedPermissionKeys.value)
            message.success('权限分配成功')
            closePermissionModal()
        } catch (error) {
        } finally {
            permissionModalLoading.value = false
        }
    }

    // 暴露给父组件的属性和方法
    defineExpose({
      activeCategory,
      checkedPermissionKeys,
      visible,
      isCheckedAll
    })
    
</script>


<style scoped>
.role-management-container {
  padding: 24px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h1 {
  font-size: 20px;
  font-weight: 600;
  margin-bottom: 8px;
}

.page-header p {
  color: #666;
  margin-bottom: 16px;
}

.header-actions {
  display: flex;
  align-items: center;
}

.stat-card {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
}

.stat-info p:first-child {
  color: #666;
  font-size: 14px;
  margin-bottom: 8px;
}

.stat-info h3 {
  font-size: 24px;
  font-weight: 600;
  margin: 0 0 8px 0;
}

.stat-trend {
  font-size: 12px;
  display: flex;
  align-items: center;
}

.stat-trend.up {
  color: #52c41a;
}

.stat-trend.down {
  color: #faad14;
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
}

.stat-icon.total {
  background-color: #e6f7ff;
  color: #1890ff;
}

.stat-icon.active {
  background-color: #f6ffed;
  color: #52c41a;
}

.stat-icon.pending {
  background-color: #fff7e6;
  color: #faad14;
}

.stat-icon.new {
  background-color: #f0f2ff;
  color: #722ed1;
}

.table-actions {
  display: flex;
  gap: 8px;
}

.permission-categories {
  height: 100%;
  display: flex;
  flex-direction: column;
  border-right: 1px solid #e8e8e8;
  overflow: hidden;
  overflow-y: auto;
}

.permission-categories .ant-list {
  flex: 1;
  overflow-y: auto;
}

.active-category {
  background-color: #e6f7ff;
  border-right: 3px solid #1890ff;
}

.permission-list {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding-left: 16px;
  overflow: hidden;
}

.permission-actions {
  margin-bottom: 16px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.permission-list .ant-tree {
  flex: 1;
  overflow-y: auto;
}
</style>